"""
生涯分析智能体 API 服务
提供 RESTful API 接口供前端调用
"""

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Dict, Any
import logging
from contextlib import asynccontextmanager

# 导入生涯分析智能体
from career_agent import generate_user_career_report

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("career-api")

# 请求模型
class CareerReportRequest(BaseModel):
    user_email: str

# 响应模型  
class CareerReportResponse(BaseModel):
    success: bool
    data: Dict[str, Any] = None
    error: str = None

@asynccontextmanager
async def lifespan(app: FastAPI):
    logger.info("生涯分析 API 服务启动")
    yield
    logger.info("生涯分析 API 服务关闭")

# 创建 FastAPI 应用
app = FastAPI(
    title="Career Analysis API",
    description="生涯概览报告生成服务",
    version="1.0.0",
    lifespan=lifespan
)

@app.get("/")
async def root():
    """根路径"""
    return {"message": "Career Analysis API Service", "version": "1.0.0"}

@app.get("/health")
async def health_check():
    """健康检查"""
    return {"status": "healthy", "service": "career-analysis"}

@app.post("/api/career/report", response_model=CareerReportResponse)
async def generate_career_report(request: CareerReportRequest):
    """生成用户生涯概览报告"""
    try:
        logger.info(f"收到生涯报告请求: {request.user_email}")
        
        # 调用生涯分析智能体
        report = generate_user_career_report(request.user_email)
        
        # 检查是否有错误
        if "error" in report:
            logger.warning(f"生成报告时出现错误: {report['error']}")
            return CareerReportResponse(
                success=False,
                error=report["error"]
            )
        
        logger.info(f"成功生成生涯报告: {request.user_email}")
        return CareerReportResponse(
            success=True,
            data=report
        )
        
    except Exception as e:
        logger.error(f"API 调用失败: {str(e)}")
        raise HTTPException(
            status_code=500,
            detail=f"生成生涯报告失败: {str(e)}"
        )

@app.get("/api/career/report/{user_email}", response_model=CareerReportResponse)
async def get_career_report(user_email: str):
    """通过 GET 请求获取用户生涯报告"""
    try:
        logger.info(f"收到 GET 生涯报告请求: {user_email}")
        
        # 调用生涯分析智能体
        report = generate_user_career_report(user_email)
        
        # 检查是否有错误
        if "error" in report:
            logger.warning(f"生成报告时出现错误: {report['error']}")
            return CareerReportResponse(
                success=False,
                error=report["error"]
            )
        
        logger.info(f"成功生成生涯报告: {user_email}")
        return CareerReportResponse(
            success=True,
            data=report
        )
        
    except Exception as e:
        logger.error(f"API 调用失败: {str(e)}")
        raise HTTPException(
            status_code=500,
            detail=f"生成生涯报告失败: {str(e)}"
        )

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "career_api:app",
        host="0.0.0.0",
        port=8002,
        reload=True,
        log_level="info"
    )
